package com.gdhz.xiaohengqin.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gdhz.xiaohengqin.device.constants.WieGandConstant;
import com.gdhz.xiaohengqin.device.model.QrCodeData;
import com.gdhz.xiaohengqin.events.PassthroughDataEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
 * @author Swallows
 * @date 2025-05-30 16:05
 */
@Slf4j
@Component
public class PassthroughDataHandler implements MessageHandler {

    private final ObjectMapper mapper;
    private final ApplicationEventPublisher publisher;

    public PassthroughDataHandler(ObjectMapper mapper, ApplicationEventPublisher publisher) {
        this.mapper = mapper;
        this.publisher = publisher;
    }

    @Override
    public boolean canHandle(JsonNode message) {
        return message.get(0).has(WieGandConstant.MESSAGE_TYPE_QRCODE);
    }

    @Override
    public Mono<Void> handle(JsonNode message) {

        return Flux.fromIterable(message::elements)
                .flatMap(element -> Mono.just(mapper.convertValue(element, QrCodeData.class)))//转换数据
                .subscribeOn(Schedulers.boundedElastic())
                .doOnNext(qrCodeData ->
//                        推送事件
                        publisher.publishEvent(new PassthroughDataEvent(qrCodeData))
                )
                .onErrorResume(e -> {
                    log.error(" 处理QR数据失败: {}", message, e);
                    return Mono.empty();
                })
                .then();
    }
}
